<?php
// This controller handles the logic for the my auctions page

class AuctionsController extends Controller
{
/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * Description: This method renders the buyer auctions page if the guest is logged in and is a buyer. If the user is not a buyer
	 * then the user will not be given access to the page. If the viewer is not logged in, then the application will redirect the view
	 * to the login page.
	 * Returns: Nothing
	 */
	public function actionBuyer()
	{
		if(Yii::app()->user->isGuest)
		{
			echo "Please Login first. We will redirect you to the login page in 3 secs";
			header("refresh:3;url=".Yii::app()->request->baseUrl);
		}
		else if(Yii::app()->user->userType=='s')
		{
			echo "you have no authority to view the buyer page";
		}
		else
		{
			$activeauctionsDataProvider = new CActiveDataProvider('Auctions', array(
								'criteria'=>array(
										'condition'=>'status_ID='.AuctionStatus::$OPEN.' and user_ID='.Yii::app()->user->userID,
										'with'=>array('tank', 'site', 'product'),
									),
								'pagination'=>array(
										'pageSize'=>8,
									),
								)
							);
			$openordersDataProvider = new CActiveDataProvider('Orders', array(
								'criteria'=>array(
										'condition'=>'t.status_ID='.AuctionStatus::$OPEN.' and auction.user_ID='.Yii::app()->user->userID,
										'with'=>array('auction', 'auction.tank', 'auction.site', 'auction.product'),
									),
								'pagination'=>array(
										'pageSize'=>8,
									),
								)
							);
			$auctionhistoryDataProvider = new CActiveDataProvider('Auctions', array(
								'criteria'=>array(
										'condition'=>' t.user_ID='.Yii::app()->user->userID.' and order.status_ID='.AuctionStatus::$CLOSED,
										'with'=>array('product', 'site', 'tank', 'order'),
									),
								'pagination'=>array(
										'pageSize'=>8,
									),
								)
							);
			$this->render("buyer", array('activeauctionsDataProvider'=>$activeauctionsDataProvider, 'openordersDataProvider'=>$openordersDataProvider, 'auctionhistoryDataProvider'=>$auctionhistoryDataProvider));
		}
	}
	
	/*
	 * called when select a row in bid auctions table
	 * retrieve the bid response table and other info like wining price and so on
	 */
	public function actionBidAuctions()
	{
		if(Yii::app()->request->isAjaxRequest&&isset($_GET['auction_ID']))
		{
			$bidAuctionsDataProvider = new CActiveDataProvider('BidAuctions', array(
								'criteria'=>array(
										'condition'=>'auction_ID='.$_GET['auction_ID'],
									//	'with'=>array('site', 'product'),
									),
								'pagination'=>array(
										'pageSize'=>4,
									),
								'sort'=>array(
										'defaultOrder'=>'delivered_price_per_gallon ASC',
									),
								)
							);
			
			$result = CActiveForm::widget('zii.widgets.grid.CGridView', array(
			    	'dataProvider'=>$bidAuctionsDataProvider,
			    	'id'=>'BidAuctionTable',
			    	'selectableRows'=>1,
			    	'selectionChanged'=>'function(id) {
			    	}',
					'columns'=>array(
			    		array(
			    			'name'=>'bidder',
			    			'value'=>'"bidder #".($row+1)',
			    		),
			    		array(
			    			'name'=>'price per gallon',
			    			'value'=>'$data->delivered_price_per_gallon',
			    		),
			    	),
				),
				true//captureOutput
			);
			if(isset($_GET['ajax'])&&$_GET['ajax']=='BidAuctionTable')
			{
				echo $result;
				return;
			}
			
			$bidAuctionsInfo = BidAuctions::model()->getMinPrice($_GET['auction_ID']);
			$user_ID = $bidAuctionsInfo[0];
			$winningPrice = $bidAuctionsInfo[1];
			$auction=Auctions::model()->findByPk($_GET['auction_ID']);
			$rackPrice = RackProducts::model()->getCurMinPrice($auction->product_ID);//today's lowest price in market
			echo CJSON::encode(array($result, $user_ID, $winningPrice, $rackPrice, $auction->tank_ID, $auction->site_ID));
		}
	}
	/*
	 * ajax call to retrieve auction info to display by given an auction ID
	 */
	public function actionAuctionHistory()
	{
		if(Yii::app()->request->isAjaxRequest&&isset($_GET['auction_ID']))
		{
			$auction=Auctions::model()->model()->findByPk($_GET['auction_ID'])->with('product','tank');
			//format the time
			$auction->auction_start=date("Y-m-d g:ia", strtotime($auction->auction_start));
			$auction->auction_end=date("Y-m-d g:ia", strtotime($auction->auction_end));
			$auction->delivery_due=date("Y-m-d g:ia", strtotime($auction->delivery_due));
			$product=$auction->product;
			$tank=$auction->tank;
			echo CJSON::encode(array($auction, $product, $tank));
		}
	}
	/*
	 * ajax call to retrieve auction info to display by given an order ID
	 */
	public function actionOpenOrders()
	{
		if(Yii::app()->request->isAjaxRequest&&isset($_GET['order_ID']))
		{
			$auction=Orders::model()->model()->findByPk($_GET['order_ID'])->with('auction')->auction;
			//format the time
			$auction->auction_start=date("Y-m-d g:ia", strtotime($auction->auction_start));
			$auction->auction_end=date("Y-m-d g:ia", strtotime($auction->auction_end));
			$auction->delivery_due=date("Y-m-d g:ia", strtotime($auction->delivery_due));
			$product=$auction->product;
			$tank=$auction->tank;
			echo CJSON::encode(array($auction, $product, $tank));
		}
	}
	
	/*
	 * called when close an order
	 */
	public function actionCloseOrder()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$order = new Orders();
			$order->scenario='buyer-update';
			$order->order_ID=$_POST['order_ID'];
			$order->buyer_net_gallons=$_POST['net_gallons'];
			$order->buyer_gross_gallons=$_POST['gross_gallons'];
			if($order->validate())
			{
				//update buyer gallons and close time;
				Orders::model()->updateByPk($order->order_ID, array('buyer_gross_gallons'=>$order->buyer_gross_gallons, 'buyer_net_gallons'=>$order->buyer_net_gallons, 'buyer_close_time'=>date('Y-m-d H:i:s')) );
				//send buyer close order notification email
				try
				{
					$data = array();
					$data['auction_ID'] = Orders::model()->findByPk($order->order_ID)->auction_ID;
					
					//Need auction object
					$email = new Email();
					$emailTOSUPPLIER=Orders::model()->with('user')->findByPk($order->order_ID)->user->emailAddress;
					$email->sendEmail($emailTOSUPPLIER, 'EKOS-ADMIN', 'CLOSE ORDER NOTIFICATION', Email::$BUYER_CLOSE, $data);
				}
				catch(Exception $e){}
				//update the order status to close if the supplier has closed it
				Orders::model()->updateByPk($order->order_ID, array('status_ID'=>AuctionStatus::$CLOSED)
					, 'supplier_close_time is not NULL and supplier_net_gallons='.$_POST['net_gallons'].' and supplier_gross_gallons='.$_POST['gross_gallons']);
				echo CJSON::encode('close-order-success');
			}
			else
				echo CJSON::encode($order->errors);
		}
	}
	
	/*
	 * called when place an order
	 */
	public function actionInsertOrder()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$order=new Orders;
			$order->user_ID=$_POST['user_ID'];
			$order->auction_ID=$_POST['auction_ID'];
			$order->status_ID=AuctionStatus::$OPEN;
			date_default_timezone_set('America/New_York');
			$order->open_time=date('Y-m-d H:i:s');
			$transaction = Yii::app()->db->beginTransaction();
			try
			{
				if($order->save())
				{
					//close auction
					Auctions::model()->updateByPk($_POST['auction_ID'], array('status_ID'=>AuctionStatus::$CLOSED));
					$transaction->commit();
					//send notification email
					try
					{
						$data = array();
						$data['auction_ID'] = $_POST['auction_ID'];
						
						$email = new Email();
						$emailTO=$order->user->emailAddress;
						$email->sendEmail($emailTO, 'EKOS-ADMIN', 'PLACE ORDER NOTIFICATION', Email::$BUYER_OPEN, $data);
					}
					catch(Exception $e){}					
					echo CJSON::encode('place-order-success');
				}
				else
				{
					foreach($order->errors as $error)
					{
						echo CJSON::encode($error);
						$transaction->rollBack();
					}
				}
			}
			catch(Exception $e)
			{
				$transaction->rollBack();
			}
		}
	}

	/**
	 * Description: This method makes an ajax call to retrieve bid auction details from the database
	 * Returns: The specified bid auction
	 * Note: This may require some security steps to block out users who type in url without logging in
	 */
	public function actionBidResponse()
	{
		$userID = $_GET['user_ID'];
		$auctionID = $_GET['auction_ID'];
		
		if(Yii::app()->request->isAjaxRequest&&isset($userID)&&isset($auctionID))
		{			
			// gets auction details for bid response			
			$result = BidAuctions::model()->getAuction($userID, $auctionID);

			$auction = array();
			
			foreach ($result as $row) {
				$auction['auction_ID'] = $auctionID;
				$auction['fuel_cost_per_gallon'] = $row->fuel_cost_per_gallon;
				$auction['freight_cost_per_gallon'] = $row->freight_cost_per_gallon;
				$auction['ancillary_fees'] = $row->ancillary_fees;
				$auction['fed_excise_tax'] = $row->fed_excise_tax;
				$auction['fed_lust'] = $row->fed_lust;
				$auction['fed_oil_spill_fee'] = $row->fed_oil_spill_fee;
				$auction['nc_road_tax'] = $row->nc_road_tax;
				$auction['nc_wholesale'] = $row->nc_wholesale;
				$auction['nc_inspection'] = $row->nc_inspection;
				$auction['nc_tare'] = $row->nc_tare;
				$auction['delivered_price_per_gallon'] = $row->delivered_price_per_gallon;
			}
			
			if (!empty($result)) {
				// gets user's first and last name
				$organizationID = Users::model()->getOrganizationID($userID);
				$auction['name'] = Organizations::model()->getOrganizationName($organizationID);
				
				// gets other details for auction
				$result = Auctions::model()->getAuction($_GET['auction_ID']);
				
				foreach ($result as $row) {
					$auction['gallon'] = $row->gallon;
					$auction['delivery_due'] = $row->delivery_due;
					$auction['delivery_due_time']= date('g:i a', strtotime($row->delivery_due));
					$auction['delivery_due_date']= date('Y-m-d', strtotime($row->delivery_due));
				}
			}
			else
				$auction = null;
			
			echo CJSON::encode($auction);
		}
	}
	
	/*
	 * called to retrieve the site details info
	 */
	public function actionSiteDetails()
	{
		if(Yii::app()->request->isAjaxRequest)
		{
			$siteID=$_POST['site_ID'];
			$tankID=$_POST['tank_ID'];
			$tank=Tanks::model()->with('tankType', 'tankPosition')->findByPk($tankID);
			$site=Sites::model()->with('rack', 'sitetoolRelation.tool')->findByPk($siteID);
			$rack=$site->rack;
			$tools=array();
			foreach($site->sitetoolRelation as $sitetoolRelation)
				$tools[]=$sitetoolRelation->tool;
			$tankMonitor=null;
			if($tank->tank_monitor_ID!=null)
			{
				$tankMoniter=$tank->tankMonitor;
			}
			echo CJSON::encode(array($tank, $site, $rack, $tools, $tank->tankType, $tank->tankPosition, $tankMonitor));
		}
	}
}
?>
